import os
import configparser
from typing import Optional
from pathlib import Path

# 获取项目根目录
BASE_DIR = Path(__file__).resolve().parent.parent.parent
# 获取配置目录
CONFIG_DIR = Path(__file__).resolve().parent

# 应用配置类
class Settings:
    # 基础配置
    APP_NAME: str = "Guzian Website"
    APP_VERSION: str = "1.0.0"
    API_V1_STR: str = "/api/v1"
    
    # 安全配置
    SECRET_KEY: str = os.getenv("SECRET_KEY", "guzian-your-secret-key-here-change-in-production")
    ALGORITHM: str = "HS256"
    ACCESS_TOKEN_EXPIRE_MINUTES: int = 30
    
    # 数据库配置
    DATABASE_URL: str = os.getenv("DATABASE_URL", "sqlite:///./guzian_app/guzian.db")
    
    # 静态文件配置
    STATIC_DIR: str = "/static"
    UPLOAD_DIR: str = os.path.join("static", "uploads", "icons")
    
    # 静态网页配置
    STATIC_FILE_UPLOAD_PATH: str = os.path.join("static", "pages")
    
    # 不限制文件扩展名
    ALLOWED_EXTENSIONS: set = set()  # 空集合表示不限制
    
    # 最大文件大小（MB）- 设置为一个很大的值，实际上不限制
    MAX_FILE_SIZE: int = 1000000  # 1TB
    
    # 默认用户配置
    DEFAULT_USERNAME: str = "admin"
    DEFAULT_PASSWORD: str = "admin123"
    
    # 分页配置
    PAGE_SIZE: int = 20

# 创建设置实例
settings = Settings()

# 获取配置函数
def get_config(config_file: str = "config.ini") -> dict:
    """读取INI配置文件并返回配置字典"""
    # 首先尝试从配置目录读取
    config_path = os.path.join(CONFIG_DIR, config_file)
    
    # 如果配置目录中没有配置文件，尝试从项目根目录读取（兼容旧路径）
    if not os.path.exists(config_path):
        config_path = os.path.join(BASE_DIR, config_file)
    
    # 创建配置解析器
    config = configparser.ConfigParser()
    
    # 读取配置文件
    if os.path.exists(config_path):
        config.read(config_path, encoding='utf-8')
        print(f"成功读取配置文件: {config_path}")
    else:
        print(f"警告: 配置文件不存在: {config_path}")
    
    # 转换为字典格式
    config_dict = {}
    for section in config.sections():
        config_dict[section] = {}
        for key, value in config.items(section):
            # 尝试将数值字符串转换为对应类型
            if value.isdigit():
                value = int(value)
            elif value.strip().lower() in ('true', 'false'):
                value = value.strip().lower() == 'true'
            config_dict[section][key] = value
    
    # 如果没有读取到配置，返回默认配置
    if not config_dict:
        config_dict = {
            'app': {
                'app_name': '子鞍的个人网站',
                'app_version': '1.0.0'
            },
            'database': {
                'database_url': 'sqlite:///./guzian_app/guzian.db'
            },
            'security': {
                'secret_key': 'guzian_secret_key_here_please_change_in_production',
                'algorithm': 'HS256',
                'access_token_expire_minutes': 30
            },
            'server': {
                'host': '0.0.0.0',
                'port': 8000
            },
            'upload': {
                'upload_dir': 'uploads/icons',
                'max_file_size': 1099511627776,  # 1TB
                'allowed_extensions': ''  # 空字符串表示不限制
            },
            'default': {
                'default_username': 'admin',
                'default_password': 'admin123',
                'page_size': 20
            }
        }
    
    return config_dict

# 加载配置
config_data = get_config()

# 从配置文件更新设置
if "database" in config_data and "database_url" in config_data["database"]:
    settings.DATABASE_URL = config_data["database"]["database_url"]

if "security" in config_data and "secret_key" in config_data["security"]:
    settings.SECRET_KEY = config_data["security"]["secret_key"]

if "security" in config_data and "access_token_expire_minutes" in config_data["security"]:
    settings.ACCESS_TOKEN_EXPIRE_MINUTES = config_data["security"]["access_token_expire_minutes"]

if "default" in config_data and "page_size" in config_data["default"]:
    settings.PAGE_SIZE = config_data["default"]["page_size"]

# 导出常用配置
DATABASE_URL = settings.DATABASE_URL
SECRET_KEY = settings.SECRET_KEY
ALGORITHM = settings.ALGORITHM
ACCESS_TOKEN_EXPIRE_MINUTES = settings.ACCESS_TOKEN_EXPIRE_MINUTES
STATIC_DIR = settings.STATIC_DIR
UPLOAD_DIR = settings.UPLOAD_DIR
STATIC_FILE_UPLOAD_PATH = settings.STATIC_FILE_UPLOAD_PATH
ALLOWED_EXTENSIONS = settings.ALLOWED_EXTENSIONS
MAX_FILE_SIZE = settings.MAX_FILE_SIZE
DEFAULT_USERNAME = settings.DEFAULT_USERNAME
DEFAULT_PASSWORD = settings.DEFAULT_PASSWORD
PAGE_SIZE = settings.PAGE_SIZE

# 确保目录存在
os.makedirs(settings.UPLOAD_DIR, exist_ok=True)
os.makedirs(settings.STATIC_FILE_UPLOAD_PATH, exist_ok=True)